import base from "@/config/baseUrl";
import {
	license
} from "@/utils/license";

export const checkUpdate = () => {
	// #ifdef  APP-PLUS
	// console.log(' license-->', license);
	// console.log('base', base);

	const obj = {
		numszs: 0,
		texts: '',
		newAppInfo: {},
		licenseName: `l_${license}`
	}

	uni.request({
		url: base.baseUrl + "api/index/check_app_update",
		success: (res) => {
			// console.log('更新信息', res.data?.data);
			if (res?.data?.data) {
				obj.newAppInfo = res.data.data[obj.licenseName];
				loadWgt(obj);
			}
		},
		fail: (err) => {
			console.error('请求失败', err);
		}
	})
	// #endif
}


const loadWgt = (obj) => {
	// #ifdef  APP-PLUS
	plus.runtime.getProperty(plus.runtime.appid, function(info) {
		const sysversion = obj.newAppInfo.version_code
		const localHotVersion = uni.getStorageSync('hot_version')
		const localversion = localHotVersion ? localHotVersion : info.versionCode
		
		// console.log(sysversion, localversion, '-----===>>-----');
		if (Number(sysversion) > Number(localversion)) {
			togx(obj);
			uni.setStorageSync('hot_version', sysversion);
		}
	});
	// #endif
}


const togx = (obj) => {
	// #ifdef  APP-PLUS
	// console.log('obj-->', obj.newAppInfo.download_url, obj.newAppInfo.licensename);
	const downloadUrl = encodeURI(obj.newAppInfo.download_url);
	// console.log('下载地址:', downloadUrl);
	
	const parts = obj.newAppInfo.download_url.split('/'); // 按 '/' 分割
	const filename = parts[parts.length - 1]; 
	
	plus.runtime.getProperty(plus.runtime.appid, (info) => {
		const downloadTask = plus.downloader.createDownload(downloadUrl, {
			filename: '_downloads/' + filename,
			method: 'GET',
			headers: {
				'User-Agent': 'Mozilla/5.0',
				'Accept': '*/*'
			}
		}, function(d, status) {
			console.log(d);
			console.log(status);
			// plus.nativeUI.showWaiting('正在更新中，请稍后...');
			if (status === 200) {
				console.log('下载成功:->', d.filename);
				installWgt(d.filename); // 安装 WGT
			} else {
				console.error('下载失败:', status);
			}
		})

		downloadTask.addEventListener('statechanged', (task, status) => {
			console.log('状态变化：', {
				status,
				state: task.state,
				downloadedSize: task.downloadedSize,
				totalSize: task.totalSize
			})
		})

		downloadTask.start()
	})
	// #endif
}

const installWgt = (filePath)=>{
	// plus.nativeUI.showWaiting('正在安装更新....');
	    plus.runtime.install(filePath, { force: true }, () => {
	        // plus.nativeUI.closeWaiting();
	        plus.nativeUI.alert('更新成功，即将重启应用', () => {
	            plus.runtime.restart();
	        });
	    }, (e) => {
	        // plus.nativeUI.closeWaiting();
	        console.error('安装失败:', e);
	        plus.nativeUI.alert('更新失败: ' + e.message);
	    });
}